package com.wjs.gulimall.auth.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.wjs.gulimall.auth.Feigin.MemberFeignService;
import com.wjs.gulimall.auth.utils.HttpUtils;
import com.wjs.gulimall.auth.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理Gitee第三方登录接口
 */

@Controller
@Slf4j
public class Oauth2GiteeController {

    @Autowired
    private MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/weibo/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> map=new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","b1903d9c66497906115488d535417f2aa3a34ab793a30beb29a9107d21fa5147");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("client_secret","ccb43abc3418f96ad8cc7ffa29e35cbac651811a4cf890234298bec7087fcf6b");
        //根据code获取token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
        if(response.getStatusLine().getStatusCode()==200){
            //获取成功
            String json = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);
            //拿到Access_Token
            String access_token = socialUserVo.getAccess_token();
            R oauthlogin = memberFeignService.oauthlogin(socialUserVo);
            if(oauthlogin.getCode()==0){
                //登录成功跳到首页
                MemberRespVo data = (MemberRespVo) oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                log.info("登录成功，数据为{}",data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
